package com.shuziren.controller.candidate;


import com.alibaba.excel.EasyExcel;

import com.shuziren.abnormal.CustomException;
import com.shuziren.core.vo.Result;
import com.shuziren.domain.dto.CandidateAddDto;
import com.shuziren.domain.dto.CandidateSelectDto;
import com.shuziren.domain.dto.CandidateUpdateDto;
import com.shuziren.domain.dto.Resume;
import com.shuziren.service.CandidateService;
import com.shuziren.service.Impl.ResumeDataListener;
import com.shuziren.service.ResumeRepository;
import com.shuziren.service.util.FileParser;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/candidate")
public class  CandidateController {
    private static final String UPLOAD_DIR = "uploads/";

    @Value("${file.upload.path}")
    private String uploadPath;

    @Autowired
    private ResumeRepository resumeRepository;

    @Autowired
    private FileParser fileParser;

    private final CandidateService candidateService;


    //全查 分页 mybatis-plus

    /**
     * 候选人条件查询
     * @param candidateDto
     * @return
     */

    @PostMapping("/getCandidateList")
    public Result getCandidateList(@RequestBody @Validated CandidateSelectDto candidateDto) {

//         candidateService.selectPage(candidateDto);

        return Result.success(candidateService.selectPage(candidateDto));
    }

    /**
     *  根据id查询
     * @param id
     * @return
     */
    @GetMapping("/getCandidateById/{id}")
    public Result getCandidateById(@PathVariable("id") Integer id) {
        if (candidateService.getById(id)==null){
            return Result.fail("该用户不存在");
        }

        return Result.success(candidateService.getById(id));
    }

    /**
     * 添加候选人
     * @param candidateAddDto
     * @return
     */
    @PostMapping("/addCandidate")
    public Result addCandidate(@RequestBody @Validated CandidateAddDto candidateAddDto){
        try {
            candidateService.addCandidate(candidateAddDto);
        } catch (Exception e) {
            throw new CustomException("添加失败,名字不能重复");
        }
        return Result.success("添加成功");
    }


    /**
     *  修改候选人
     * @param candidateUpdateDto
     * @return
     */
    @PostMapping("/updateCandidate")
    public Result updateCandidate(@RequestBody @Valid CandidateUpdateDto candidateUpdateDto) {
        if (candidateService.getById(candidateUpdateDto.getId()) ==null){
            return Result.fail("用户不存在 仅后端测试使用，出现此报错就是数据库没有这个id字段，前端不会展示数据库中没有的字段");
        }
         candidateService.updateCandidate(candidateUpdateDto);

         return Result.success("修改成功");
    }

    /**
     * 删除候选人
     * @param id
     * @return
     */


    @GetMapping("/deleteCandidate/{id}")
    public Result deleteCandidate(@PathVariable("id") Integer id) {
        if (candidateService.getById(id)==null){
            return Result.fail("该用户不存在");
        }
         candidateService.removeById(id);
        return Result.success("删除成功");
    }

    //上传文件

    /**
     * 简历上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public String uploadResume(@RequestParam("file") MultipartFile file) {
        log.info("开始处理文件上传，文件名: {}", file.getOriginalFilename());
        log.info("文件大小: {} bytes", file.getSize());
        log.info("文件类型: {}", file.getContentType());

        if (file.isEmpty()) {
            log.warn("上传文件为空");
            return "请选择文件";
        }

        try {
            // 确保上传目录存在
            File uploadDir = new File(uploadPath);
            log.info("上传目录路径: {}", uploadPath);
            if (!uploadDir.exists()) {
                log.info("创建上传目录");
                boolean created = uploadDir.mkdirs();
                if (!created) {
                    log.error("创建上传目录失败");
                    return "创建上传目录失败";
                }
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + extension;
            log.info("生成新文件名: {}", newFileName);

            // 保存文件
            File dest = new File(uploadPath + File.separator + newFileName);
            log.info("文件保存路径: {}", dest.getAbsolutePath());
            file.transferTo(dest);

            // 根据文件类型选择解析方式
            String fileName = dest.getName().toLowerCase();
            log.info("开始解析文件，文件类型: {}", fileName);

            if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")) {
                log.info("使用EasyExcel解析Excel文件");
                EasyExcel.read(dest, Resume.class, new ResumeDataListener()).sheet().doRead();
            } else if (fileName.endsWith(".docx") || fileName.endsWith(".pdf")) {
                log.info("使用FileParser解析Word或PDF文件");
                Resume resume = fileParser.parseFile(dest);
                if (resume != null) {
                    log.info("解析成功，保存简历信息");
                    resumeRepository.save(resume);
                } else {
                    log.warn("文件解析失败，未获取到简历信息");
                    return "文件解析失败，请检查文件格式是否正确";
                }
            } else {
                log.warn("不支持的文件类型: {}", fileName);
                return "不支持的文件类型";
            }

            log.info("文件上传和处理完成");
            return "文件上传成功，文件名: " + newFileName;
        } catch (IOException e) {
            log.error("文件处理失败", e);
            return "文件上传失败: " + e.getMessage();
        } catch (Exception e) {
            log.error("处理过程中发生未知错误", e);
            return "处理过程中发生错误: " + e.getMessage();
        }
    }


}





